package com.itheima.web.filter;

import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import com.itheima.utils.CookieUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class AutoLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;

        // 优化:若优化已经登录了, 则获取cookie,查询数据库代码则没有必要执行
        HttpSession session = request.getSession();
        Object u = session.getAttribute("user");
        if (u != null) {
            // 说明已经登录了
            chain.doFilter(req, resp);
            return;
        }


        //1. 获取所有的Cookie数组
        Cookie[] cookies = request.getCookies();

        //2. 查找名称为autoLoginCookie对象
        Cookie cookie = CookieUtils.findCookieByName(request, "autoLoginCookie");

        //3. 判断cookie是否为空
        if (cookie == null) {
            // 直接放行
            chain.doFilter(req, resp);
            return;
        }

        //4.有cookie对象, 获取Cookie的值, 查询数据库
        String value = cookie.getValue(); // jack&1234

        User user = new User();
        user.setUsername(value.split("&")[0]);
        user.setPassword(value.split("&")[1]);

        UserService service = new UserServiceImpl();
        User existUser = service.login(user);

        //5.判断flag
        if (existUser == null) {
            // 有cookie, 但是cookie数据过期了
            chain.doFilter(req, resp);
            return;
        }

        //6. 有cookie, 登录成功了
        request.getSession().setAttribute("user", existUser);
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
